//
//  main.cpp
//  TexMerger
//
//  Created by XingXavier on 15/4/22.
//  Copyright (c) 2015年 Xstereo. All rights reserved.
//

#include <iostream>
#include <fstream>
#include <time.h>
using namespace std;

const string currentDateTime();
const void cropExtension(string*,string);

int main(int argc, const char * argv[]) {
    string fname = string(argv[1]);
    cropExtension(&fname,".tex");
    string nfname = fname + "_merged_" + currentDateTime() + ".tex";
    fname = fname +".tex";
    ifstream in(fname);
    ofstream out(nfname);
    const string inpu = "\\input{";
    const string incl = "\\include{";
    
    if (!in)
    {
        cerr << "Could not open " << fname << "\n";
        return 1;
    }
    
    if (!out)
    {
        cerr << "Could not create " << nfname << "\n";
        return 1;
    }
    
    string line;
    while (getline(in,line)){
        size_t cpos=line.find('%');
        string lineori=line;
        line=line.substr(0,cpos);
        size_t pos;
        if ((pos = line.find(inpu)) != string::npos){
            pos = pos + inpu.length();
            size_t posend = line.find('}',pos);
            string subfilename = line.substr(pos,posend-pos);
            cropExtension(&subfilename, ".tex");
            subfilename=subfilename+".tex";
            ifstream insub(subfilename);
            if (!insub){
                cerr << "Couldn't open subfile " << subfilename << ", commenting the line \'" << line << "\'\n" ;
                out << "%"+lineori << '\n';
            }else{
                out << "%"+lineori << '\n';
                string newline;
                while (getline(insub,newline)){
                    out << newline << '\n' ;
                }
            }
        }else if ((pos = line.find(incl)) != string::npos){
            pos = pos + incl.length();
            size_t posend = line.find('}',pos);
            string subfilename = line.substr(pos,posend-pos);
            cropExtension(&subfilename, ".tex");
            subfilename=subfilename+".tex";
            ifstream insub(subfilename);
            if (!insub){
                cerr << "Couldn't open subfile " << subfilename << ", ignoring the line \'" << line << "\'\n" ;
                out << "%"+lineori << '\n';
            }else{
                out << "%"+lineori << '\n';
                out << "\\pagebreak\n" ;
                string newline;
                while (getline(insub,newline)){
                    out << newline << '\n' ;
                }
            }
        }else{
            out << lineori << '\n' ;
        }
        
    }
    string texeditordir=string(argv[2]);
    string open=texeditordir+" "+nfname;
    const char* openintexeditor=open.c_str();
    system(openintexeditor);
    return 0;
}


//filename is the name to be cropped, ext is the extension containing ".", e.g. ".tex"
const void cropExtension(string * filename,string ext){
    if(filename->substr(filename->length() - ext.length(),filename->length()) == ext){
        *filename = filename->substr(0,filename->length()-ext.length());
    }
}


const string currentDateTime() {
    time_t     now = time(0);
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);
    // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
    // for more information about date/time format
    strftime(buf, sizeof(buf), "%Y%m%d_%H_%M_%S", &tstruct);
    
    return buf;
}